{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "7dd2e144",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import classification_report,roc_auc_score\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e7e09f2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1.获取数据\n",
    "# 下载地址 https://archive.ics.uci.edu/dataset/15/breast+cancer+wisconsin+original\n",
    "names=[\"Sample code number\",\"Clump Thickness\",\"Uniformity of Cell Size\",\"Uniformity of Cell Shape\",\"Marginal Adhesion\",\"Single Epithelial Cell Size\",\"Bare Nuclei\",\"Bland Chromatin\",\"Normal Nucleoli\",\"Mitoses\",\"Class\"]\n",
    "data=pd.read_csv(\"E:\\\\pythonProject\\\\ai-study\\\\逻辑回归学习\\\\example\\\\breast-cancer-wisconsin.data\",names=names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c0249460",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 基本数据处理，处理缺失值，数据中缺失值用 ? 标识，需要替换成nan，然后删除\n",
    "data=data.replace(to_replace=\"?\",value=np.nan)\n",
    "data=data.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7ab3b3e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 确定特征值（特征字段为前面2~10行,即除去第一行样本编号和最后一个目标值）\n",
    "x=data.iloc[:,1:-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "444d775d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 目标值\n",
    "y=data.iloc[:,-1] # y = data[\"Class\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dc306d1d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 分割数据\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=22,test_size=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1fcbac94",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3.特征工程（标准化）\n",
    "transfer=StandardScaler()\n",
    "x_train=transfer.fit_transform(x_train)\n",
    "x_test=transfer.fit_transform(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7f663726",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {color: black;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>LogisticRegression()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">LogisticRegression</label><div class=\"sk-toggleable__content\"><pre>LogisticRegression()</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "LogisticRegression()"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4.机器学习（逻辑回归）\n",
    "estimator=LogisticRegression()\n",
    "estimator.fit(x_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5b605898",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "准确率= 0.9854014598540146\n"
     ]
    }
   ],
   "source": [
    "result=estimator.score(x_test,y_test)\n",
    "print(\"准确率=\",result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f2e5da3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测值= [2 4 4 2 2 2 2 2 2 2 2 2 2 4 2 2 4 4 4 2 4 2 4 4 4 2 4 2 2 2 2 2 4 2 2 2 4\n",
      " 2 2 2 2 4 2 4 4 4 4 2 4 4 2 2 2 2 2 4 2 2 2 2 4 4 4 4 2 4 2 2 4 2 2 2 2 4\n",
      " 2 2 2 2 2 2 4 4 4 2 4 4 4 4 2 2 2 4 2 4 2 2 2 2 2 2 4 2 2 4 2 2 4 2 4 4 2\n",
      " 2 2 2 4 2 2 2 2 2 2 4 2 4 2 2 2 4 2 4 2 2 2 4 2 2 2]\n"
     ]
    }
   ],
   "source": [
    "y_pre=estimator.predict(x_test)\n",
    "print(\"预测值=\",y_pre)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "dd087c06",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "              precision    recall  f1-score   support\n",
      "\n",
      "          良性       0.99      0.99      0.99        89\n",
      "          恶性       0.98      0.98      0.98        48\n",
      "\n",
      "    accuracy                           0.99       137\n",
      "   macro avg       0.98      0.98      0.98       137\n",
      "weighted avg       0.99      0.99      0.99       137\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 分类评估报告\n",
    "report = classification_report(y_test,y_pre,labels=[2,4],target_names=[\"良性\",\"恶性\"])\n",
    "print(report)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "b899cd4c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "389    2\n",
      "32     4\n",
      "272    4\n",
      "655    2\n",
      "271    2\n",
      "      ..\n",
      "250    2\n",
      "436    4\n",
      "496    2\n",
      "645    2\n",
      "518    2\n",
      "Name: Class, Length: 137, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 把样本值转为布尔类型\n",
    "y_test=np.where(y_test>3,1,0) # 当4（恶性）的时候为true，反之"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "93bbd5cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9839653558052434\n"
     ]
    }
   ],
   "source": [
    "score=roc_auc_score(y_test,y_pre)\n",
    "print(score) #越接近1越好，越接近0.5越假"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c52231bd",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
